# _*_ coding:utf-8 _*_
# @File  : exchange_rate.py
# @Time  : 2021-07-28  13:51
# @Author: zizle


# 爬取指定日期的汇率数据
import requests
from logger import logger


class ExchangeRateSpider(object):
    SPIDER_URL = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate={}&endDate={}&currency=USD/CNY,EUR/CNY,100JPY/CNY,HKD/CNY,GBP/CNY,AUD/CNY,NZD/CNY,SGD/CNY,CHF/CNY,CAD/CNY,CNY/MYR,CNY/RUB,CNY/ZAR,CNY/KRW,CNY/AED,CNY/SAR,CNY/HUF,CNY/PLN,CNY/DKK,CNY/SEK,CNY/NOK,CNY/TRRY,CNY/MXXN,CNY/THB&pageNum=1&pageSize=10"

    def spider_exchange_rate(self, query_date):
        url = self.SPIDER_URL.format(query_date, query_date)
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
        }
        try:
            r = requests.get(url, headers=headers)
            rev_data = r.json()
        except Exception as e:
            logger.error('爬取汇率数据失败了:{}'.format(e))
            return []
        else:
            # 检验数据
            head = rev_data.get('head')
            if head and head.get('rep_code', '') != '200':
                logger.error('爬取汇率数据失败!状态码!=200')
                return []
            data = rev_data.get('data')
            if data['startDate'] != data['endDate']:
                logger.error('爬取汇率数据失败!数据日期超出一天!')
                return []
            rate_date = data['startDate']
            table_header = data['searchlist']
            records = rev_data.get('records')
            if len(records) > 1:
                logger.error('爬取汇率数据失败,records不止一个对象!')
                return
            table_values = records[0]['values']
            # 整理数据
            result_data = []
            for tup in list(zip(table_header, table_values)):
                result_data.append(
                    {'rate_date': rate_date, 'rate_name': tup[0], 'rate': tup[1]}
                )
            return result_data


if __name__ == '__main__':
    s = ExchangeRateSpider()
    d = s.spider_exchange_rate('2021-07-28')
    print(d)
